package com.hks360.car_treasure.widget;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.util.AttributeSet;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;

import com.hks360.car_treasure.R;

/**
 * Created by rwq on 2016/5/27.
 */
public class FenceToogleButton extends View implements View.OnClickListener{
    public FenceToogleButton(Context context) {
        super(context);
        initView();
    }

    public FenceToogleButton(Context context, AttributeSet attrs) {
        super(context, attrs);
        initView();
    }
    /**
     *1.构造方法--实例化
     *2.测量：onMeasure方法
     *3.指定View的大小和位置：onLayout方法
     *4.绘制视图：onDraw方法
     *
     * */
    private Bitmap bgClose;
    private Bitmap bgOpen;
    private Bitmap slideBitmap;
    private Paint paint;



    private boolean isOn = false;


    private OnToogleListener listener;
    /*
     * 点击事件是否生效，如果生效滑动事件无效
     * true生效
     * false无效
     */



    private void initView() {
        paint = new Paint();
        paint.setAntiAlias(true);
        bgClose = BitmapFactory.decodeResource(getResources()
                , R.drawable.close_bg);
        bgOpen = BitmapFactory.decodeResource(getResources()
                , R.drawable.open_bg);
        slideBitmap = BitmapFactory.decodeResource(getResources(),
                R.drawable.slide_pot);
        setOnClickListener(this);
    }


    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        setMeasuredDimension(bgClose.getWidth(), bgClose.getHeight());
    }
    @Override
    protected void onDraw(Canvas canvas) {
        if(isOn){
            canvas.drawBitmap(bgOpen, 0, 0,paint);
            canvas.drawBitmap(slideBitmap, bgOpen.getWidth() - slideBitmap.getWidth()  - 2, (bgOpen.getHeight() - slideBitmap.getHeight())/2,paint);
        }else {
            canvas.drawBitmap(bgClose, 0, 0,paint);
            canvas.drawBitmap(slideBitmap, 2, (bgClose.getHeight() - slideBitmap.getHeight())/2,paint);
        }
    }

    private float currentPot;
    @Override
    public boolean onTouchEvent(MotionEvent event) {
        super.onTouchEvent(event);
        switch (event.getAction()){
            case MotionEvent.ACTION_DOWN:
                currentPot = event.getX();
                break;
        }
        return true;
    }

    public void setOnToggleListener(OnToogleListener listener) {
        this.listener = listener;
    }

    @Override
    public void onClick(View v) {
        if(currentPot > bgClose.getWidth()/2){
            isOn = true;
        }else if(currentPot <= bgClose.getWidth()/2){
            isOn = false;
        }
        listener.onToogleChanged(isOn);
        invalidate();
    }

    public interface OnToogleListener {
        void onToogleChanged(boolean isOpen);
    }
}
